package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-writer/cache"
	"red-book-writer/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	author := c.PostForm("author")
	if title == "" || comment == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.Aritcle{
		Title:   title,
		Comment: comment,
		Author:  author,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	var aritcle model.Aritcle
	model.DB.Where("id = ?", data.ID).Find(&aritcle)
	jsonData, err := json.Marshal(aritcle)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var aritcle model.Aritcle
	err := model.DB.Where("id = ?", id).Find(&aritcle).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": aritcle,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var aritcle model.Aritcle
	err := model.DB.Where("id = ?", id).Delete(&aritcle).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {
	var aritcle []model.Aritcle
	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {

		model.DB.Find(&aritcle)

		jsonData, _ := json.Marshal(&aritcle)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &aritcle)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": aritcle,
	})
}
